import axios from "./index.js";

import { ElMessage, ElLoading } from "element-plus";
const loginOption = {
  lock: true,
  text: "正在加载...",
  background: "rgba(0, 0, 0, 0.7)",
};
const request = (url, method, data, params, responseType = "json", load) => {
  if (params) {
    for (let key in params) {
      if (params[key] == null) params[key] = ""
    }
  }
  let loadingInstance;
  if (!load) loadingInstance = ElLoading.service(loginOption);
  return new Promise((resolve, reject) => {
    axios({
      url,
      method,
      data,
      params,
      responseType
    })
      .then((res) => {
        if (responseType === 'blob') downloadFile(res);
        if (!load) loadingInstance.close();
        resolve(res.data);
      })
      .catch((err) => {
        if (!load) loadingInstance.close();
        reject(err.data)
      });
  });
};

const downloadFile = (res) => {
  let url = window.URL.createObjectURL(new Blob([res.data]))
  let a = document.createElement('a')
  a.style.display = 'none'
  a.href = url
  a.setAttribute('download', 'excel.xls')
  document.body.appendChild(a)
  a.click()
  window.URL.revokeObjectURL(a.href)
  document.body.removeChild(a)
}

const get = (url, params, responseType = 'json', load) => {
  return request(url, "GET", {}, params, responseType, load);
};
const post = (url, data) => {
  return request(url, "POST", data, {}, 'json', false);
};
const put = (url, data) => {
  return request(url, "PUT", data, {}, 'json', false);
};
const del = (url, params) => {
  return request(url, "DELETE", {}, params, 'json', false);
};

const api = {
  get,
  post,
  put,
  del,
};
export default api;
